from front import eval
import os
import os.path as path

def split_content(content):
    # split content into title, source and result
    lines = content.split("\n")
    # remove empty lines
    lines = [line for line in lines if line.strip()]
    # find index of lines that contain `###`
    headers = [i for i, line in enumerate(lines) if line.startswith("###")]
    tails = headers[1:] + [len(lines)]
    # print("headers: ", tails)
    # print("tails: ", tails)
    sections = [(lines[header][3:], "\n".join(lines[header+1:tails[i]])) for i, header in enumerate(headers)]
    # print("sections: ", sections)
    # first section is title and source
    title_section = sections[0]
    title = title_section[0]
    src = title_section[1]
    # second section is eval result
    eval_section = sections[1]
    res = eval_section[1].strip()
    return title, src, res
    

def test_corpus(corpus):
    # for all test files in test/corpus
    n = 0
    for f in os.listdir(corpus):
        with open(path.join(corpus, f), 'r') as file:
            print(f"  {f}:")
            n += 1
            print(f"     {n}: ", end="")
            content = file.read()
            title, src, res = split_content(content)
            r = eval(src)
            if str(r) == res or (r == True and res == "true") or (r == False and res == "false"):
                print(f"√ {title}")
            else:
                print(f"× {title}. Expected `{res}`, got `{r}`")


if __name__ == '__main__':
    corpus = path.join(path.dirname(path.dirname(__file__)), "test/corpus")
    test_corpus(corpus)